
import React, { memo, useContext, useEffect } from "react";
import { Input, Modal, Form, message } from 'antd';
import { ClassContext } from "./store";
import { createClassification, updateClassification, getClassificationDetail } from './../../api/classification';
import type { classificationFormType, classificationDetailsReqType } from './../../types/classificationType';

const AddOrEdit = (props:{getList:()=>void}) => {
    const [form] = Form.useForm();
    const { state, dispatch } = useContext(ClassContext);

    const onFinish = (e: classificationFormType) => {
        if (state.type === "addFirst" || state.type === "addSub") {
            createClassification({
                ...e,
                ...state.dataItem
            }).then(res => {
                if (res.code === 0) {
                    message.success('创建成功');
                    dispatch({ type: "CHANGE_ADDOREDIT", payLoad: false });
                    props.getList();
                }
            })
        } else {

            updateClassification({
                ...e,
                ...state.dataItem
            }).then(res => {
                if (res.code === 0) {
                    message.success('编辑成功');
                    dispatch({ type: "CHANGE_ADDOREDIT", payLoad: false });
                    props.getList();
                }
            })
        }
    }
    const handBannerDetail = (e: classificationDetailsReqType) => {
        getClassificationDetail(e).then(res => {
            if (res.code === 0) {
                form.setFieldsValue(res.data);
            }
        })
    }
    useEffect(() => {
        form.resetFields();
        if (state.addOrEdit && state.dataItem.categoryId && (state.type === "editFirst", state.type === "editSub")) {
            handBannerDetail({ categoryId: state.dataItem.categoryId })
        }
    }, [state.addOrEdit])

    return <>

        <Modal title={state.type === "addFirst" || state.type === "addSub" ? '新增' : '编辑'} open={state.addOrEdit} onOk={form.submit} onCancel={
            () => dispatch({ type: "CHANGE_ADDOREDIT", payLoad: false })
        }>
            <Form
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
                // layout="horizontal"
                onFinish={onFinish}
                form={form}
                style={{ maxWidth: 600 }}
            >
                <Form.Item<classificationFormType> name={"categoryName"} label="分类名称">
                    <Input />
                </Form.Item>
            </Form>
        </Modal>



    </>
}

export default memo(AddOrEdit)